package com.juku2024.juku.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.R
import com.juku2024.juku.SearchActivity
import com.juku2024.juku.VideoDetailActivity
import com.juku2024.juku.adapter.SearchResultAdapter
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.tools.AnalysisUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.viewmodel.SearchViewModel
import com.juku2024.juku.widget.LoadingView

class SearchResultFragment : BaseFragment() {

    private var page = 1
    private var keyWord: String? = null
    private val searchResultAdapter by lazy { SearchResultAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(requireActivity().viewModelStore, SearchViewModel::class.java) }

    private lateinit var loadingView: LoadingView
    private lateinit var searchRecycler: RecyclerView
    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_search_result, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        loadingView = rootView.findViewById(R.id.loadingView_search_result)
        searchRecycler = rootView.findViewById(R.id.searchRecycler)

        searchRecycler.layoutManager = WrapLinearLayoutManager(requireContext())
        searchRecycler.setHasFixedSize(true)
        searchRecycler.adapter = searchResultAdapter

    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        keyWord = arguments?.getString("search")?:return
        search(keyWord!!)
    }

    override fun bindEvent() {
        super.bindEvent()
        searchResultAdapter.loadMoreModule.setOnLoadMoreListener {
            doHttpSearchResult()
        }

        searchResultAdapter.setOnItemClickListener { _, _, position ->
            (requireActivity() as SearchActivity).closeKeyboard()
            //跳转到播放
            VideoDetailActivity.toVideoDetail(requireContext(), searchResultAdapter.data[position].id, searchResultAdapter.data[position].name)
        }

        searchResultAdapter.setOnItemChildClickListener { _, _, position ->
            (requireActivity() as SearchActivity).closeKeyboard()
            //跳转到播放
            VideoDetailActivity.toVideoDetail(requireContext(), searchResultAdapter.data[position].id, searchResultAdapter.data[position].name)
        }
    }

    fun search(key: String) {
        keyWord = key
        page = 1
        if (searchResultAdapter.data.isNotEmpty()) {
            searchResultAdapter.setList(ArrayList())
        }
        loadingView.showLoading()
        doHttpSearchResult()

        AnalysisUtils.analysis(Constants.EVENT_SEARCH, Constants.EVENT_SEARCH_KEY, key)
    }

    private fun doHttpSearchResult() {
        viewModel.getSearchResult(keyWord, page, {
            if (isFragmentNotActive()) return@getSearchResult
            loadingView.hideLoading()
            if (it.results.isNullOrEmpty()) { // 返回数据empty
                if (searchResultAdapter.data.isEmpty()) { // 当前还没加载内容
                    loadingView.showEmptyStatus(getString(R.string.empty_list))
                    // 统计没有搜索内容的关键词
                    AnalysisUtils.analysis(Constants.EVENT_SEARCH, Constants.KEY_SEARCH_NO_RESULT, keyWord)
                } else { // 已经加载数据
                    searchResultAdapter.loadMoreModule.loadMoreEnd()
                }
                return@getSearchResult
            }
            if (searchResultAdapter.data.isEmpty()) {
                searchResultAdapter.setList(it.results)
            } else {
                searchResultAdapter.addData(it.results!!)
            }

            if (TextUtils.isEmpty(it.next)) {
                searchResultAdapter.loadMoreModule.loadMoreEnd(searchResultAdapter.data.size < 6)
            } else {
                page++
                searchResultAdapter.loadMoreModule.loadMoreComplete()
            }
        }, {
            if (isFragmentNotActive()) return@getSearchResult
            loadingView.hideLoading()
            if (searchResultAdapter.data.isEmpty()) {
                loadingView.showErrorStatus(it, getString(R.string.retry)) {
                    loadingView.showLoading()
                    loadingView.postDelayed({
                        doHttpSearchResult()
                    }, 500)
                }
            } else {
                searchResultAdapter.loadMoreModule.loadMoreFail()
            }
        })
    }

}